<?php
class SearchForm extends CFormModel {

	public $columns = array ();
	public $operator = array ();
	public $value = array ();

	private $columns_list = null;
	private $_searchParam;

	public function rules() {
		return array ();
	}

	public function attributeLabels() {
		return array ();
	}

	public function buildCriteria() {
		$criteria = new CDbCriteria;
		$criteria->condition = "1 = 1 ";
		$criteria->params = array ();
		$conditions = array();

		if (!Yii::app()->user->checkAccess('Adviser.canAccessAllProjects'))
		{
			$conditions['adviser_initials'] = array('adviser_initials = \''.Yii::app()->user->getState('dbuser')->initials.'\'');
		}

		foreach ($this->columns as $id => $column_name){
			$condition = $this->buildCondition($id);

			if ($condition){
				if (!isset($conditions[$column_name]))
					$conditions[$column_name] = array();

				$conditions[$column_name][] = $condition;
			}
		}
		
		foreach ($conditions as $array){
			$criteria->condition .= "and (0 = 1 ";
			foreach ($array as $condition){
				$criteria->condition .= " or " . $condition;
			}
			$criteria->condition .= ") ";
		}

		Yii::log($criteria->condition, "info", "SEARCH.query");

		return $criteria;
	}

	protected function buildCondition($id) {
		if (isset ($this->columns[$id])) {
			$cond = "`" . $this->columns[$id] . "` ";

			if (!isset ($this->value[$id]) || $this->value[$id] == "") {
				$cond .= "is null";
			} else {
				if (!isset ($this->operator[$id]))
					$this->operator[$id]="=";

				switch ($this->operator[$id]) {
					case "like" :
						$this->value[$id] = "%" . $this->value[$id] . "%";
					case ">" :
					case "<" :
					case "=" :
					case "!=" :
						$cond .= $this->operator[$id] . " ";
						break;

					case "starts" :
						$this->value[$id] = $this->value[$id] . "%";
						$cond .= " like ";
						break;

					case "end" :
						$this->value[$id] = "%" . $this->value[$id];
						$cond .= " like ";
						break;
				}

				$this->getColumnsList();

				switch ($this->columns_list['types'][$this->columns[$id]]) {
					case 'integer' :
						$cond .= $this->value[$id];
						break;
					case 'date' :
						$cond .= "STR_TO_DATE('" . $this->value[$id] . "','%d/%m/%Y')";
						break;
					default :
						$cond .= "'" . str_replace("'", "\\'", $this->value[$id]) . "'";
						break;
				}
				return $cond;
			}
		}

		return false;
	}

	protected function buildLabel($name) {
		$label = null;
		if ($this->_searchParam !== null) {
			$crit = new CParameterCriteria($this->_searchParam);
			$crit->equals("COLNAM", $name);
			$res = $crit->first();
			if ($res !== false) {
				$label = Yii::t('search', $res["COLLBL"]);
			}
		}

		if ($label === null || $label == "") {
			$label = ucwords(trim(strtolower(str_replace(array (
				'-',
				'_'
			), ' ', preg_replace('/(?<![A-Z])[A-Z]/', ' \0', $name)))));
			$label = preg_replace('/\s+/', ' ', $label);
			if (strcasecmp(substr($label, -3), ' id') === 0)
				$label = substr($label, 0, -3);
			$label = Yii::t('database', $label);
		}
		return $label;
	}

	protected function buildType($name, $type) {
		$realType = null;
		if ($this->_searchParam !== null) {
			$crit = new CParameterCriteria($this->_searchParam);
			$crit->equals("COLNAM", $name);
			$res = $crit->first();
			if ($res !== false) {
				$realType = $res["COLTYP"];
			}
		}

		if ($realType === null || $realType === "") {
			$realType = $type;
		}
		return $realType;
	}

	protected function buildValues($name) {
		$values = null;
		if ($this->_searchParam !== null) {
			$crit = new CParameterCriteria($this->_searchParam);
			$crit->equals("COLNAM", $name);
			$res = $crit->first();
			if ($res !== false) {
				$values = Yii::t('search', $res["COLSQL"]);
			}

			if ($values !== null && $values != "") {
				try {
					$command = Yii::app()->db->createCommand($values);
					$values = $command->queryAll();
				} catch (Exception $e) {
					$values = null;
				}
			}
		}
		return $values;
	}

	public function getColumnsList() {
		if ($this->columns_list == null) {
			try {
				$this->_searchParam = Yii::app()->parameter->getParametersArray("SEARCH");
			} catch (Exception $e) {
				$this->_searchParam = null;
			}

			$columns = SearchItem::model()->tableSchema->columns;
			$this->columns_list = array (
				'labels' => array (),
				'values' => array (),
				'types' => array (),
			);
			foreach ($columns as $column) {
				$this->columns_list['labels'][$column->name] = $this->buildLabel($column->name);
				$this->columns_list['values'][$column->name] = $this->buildValues($column->name);
				$this->columns_list['types'][$column->name] = $this->buildType($column->name, $column->type);
			}
		}

		return $this->columns_list;
	}
}
?>


